﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;

namespace ModelBinder.Host.Infrastructures.ModelBinders;

public class CustomMultiModelBinder : IModelBinder
{
    private readonly BodyModelBinder _bodyModelBinder;
    private readonly ComplexObjectModelBinder _complexObjectModelBinder;

    public CustomMultiModelBinder(BodyModelBinder bodyModelBinder, ComplexObjectModelBinder complexObjectModelBinder)
    {
        _bodyModelBinder = bodyModelBinder;
        _complexObjectModelBinder = complexObjectModelBinder;
    }

    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var request = bindingContext.HttpContext.Request;
        if (request.ContentType!.StartsWith("multipart/form-data"))
        {
            await _complexObjectModelBinder.BindModelAsync(bindingContext);
        }
        else
        {
            await _bodyModelBinder.BindModelAsync(bindingContext);
        }
    }
}